package com.benshou.bsoa.service.yida;


import com.aliyun.dingtalkrobot_1_0.models.RobotSendDingHeaders;
import com.aliyun.dingtalkrobot_1_0.models.RobotSendDingRequest;
import com.aliyun.dingtalkrobot_1_0.models.RobotSendDingResponse;
import com.aliyun.tea.TeaException;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import com.benshou.bsoa.dto.yida.req.DingTalkMsgReq;
import com.benshou.bsoa.utils.CreateAccessTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Collections;

/*
 * 钉钉机器人服务
 * 用于处理与任务运行情况的相关逻辑
 */
@Service
public class RobotService {

    @Value("${yida_app_robot_code}")
    private String ROBOT_CODE; // 钉钉机器人编码

    @Autowired
    private CreateAccessTokenUtil createAccessTokenUtil;

    /**
     * 发送钉钉机器人消息
     * @param msgReq 消息请求对象
     * @return 发送结果响应
     * @throws Exception 可能抛出的异常
     */
    public RobotSendDingResponse sendDingRobotMessage(DingTalkMsgReq msgReq) throws Exception {
        // 创建 Client
        Config config = new com.aliyun.teaopenapi.models.Config();
        config.protocol = "https";
        config.regionId = "central";
        com.aliyun.dingtalkrobot_1_0.Client client = new com.aliyun.dingtalkrobot_1_0.Client(config);

        msgReq.setRobotCode(ROBOT_CODE); // 设置机器人编码

        // 构建 Headers（accessToken 是必须的）
        RobotSendDingHeaders headers = new RobotSendDingHeaders();
        headers.xAcsDingtalkAccessToken = createAccessTokenUtil.getToken();

        // 构建 Request
        RobotSendDingRequest request = new RobotSendDingRequest()
                .setRobotCode(msgReq.getRobotCode())
                .setRemindType(msgReq.getRemindType())
                .setReceiverUserIdList(msgReq.getUserIds())
                .setContent(msgReq.getContent());

        try {
            return client.robotSendDingWithOptions(request, headers, new RuntimeOptions());
        } catch (TeaException err) {
            throw new RuntimeException("钉钉机器人发送失败: " + err.getMessage(), err);
        } catch (Exception _err) {
            TeaException err = new TeaException(_err.getMessage(), _err);
            throw new RuntimeException("钉钉机器人发送失败: " + err.getMessage(), err);
        }
    }
}
